package com.zcj.demo.web.user.rest;

import com.zcj.demo.user.service.UserService;
import com.zcj.demo.user.service.dto.UserDTO;
import com.zcj.demo.utils.response.Response;
import com.zcj.demo.web.user.vo.UserVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * User Controller层
 *
 * @author 自动生成
 * @date 2020-10-13 16:02:43
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 分页查询
     *
     * @param pageable 分页信息
     * @param userVO   查询条件
     * @return 分页列表
     */
    @GetMapping
    public ResponseEntity<Response> findByPage(
            @PageableDefault(sort = {"lastModifiedDate"}, direction = Sort.Direction.DESC) Pageable pageable,
            UserVO userVO) {
        Page<UserDTO> response = userService.findByPage(pageable, userVO);
        return ResponseEntity.ok(Response.<UserDTO>builder().withPage(response).build());
    }

    /**
     * 条件查询所有
     *
     * @param userVO 查询条件
     * @return 所有符合条件的列表
     */
    @GetMapping("/all")
    public ResponseEntity<Response> findAll(UserVO userVO) {
        List<UserDTO> response = userService.findAll(userVO);
        return ResponseEntity.ok(Response.<UserDTO>builder().withList(response).build());
    }

    /**
     * 通过id查询
     *
     * @param id 编号
     * @return 单条数据
     */
    @GetMapping("/{id}")
    public ResponseEntity<UserDTO> findById(@PathVariable("id") String id) {
        UserDTO response = userService.findById(id);
        return ResponseEntity.ok(response);
    }

    /**
     * 创建
     *
     * @param userDTO 创建的信息
     * @return 创建的实体
     */
    @PostMapping
    public ResponseEntity<UserDTO> create(@RequestBody UserDTO userDTO) {
        UserDTO response = userService.create(userDTO);
        return ResponseEntity.ok(response);
    }

    /**
     * 更新
     *
     * @param id      编号
     * @param userDTO 更新的信息
     * @return 更新之后的实体
     */
    @PutMapping("/{id}")
    public ResponseEntity<UserDTO> update(@PathVariable("id") String id, @RequestBody UserDTO userDTO) {
        userDTO.setId(id);
        UserDTO response = userService.update(userDTO);
        return ResponseEntity.ok(response);
    }

    /**
     * 根据编号删除
     *
     * @param id 编号
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Object> delete(@PathVariable("id") String id) {
        userService.delete(id);
        return ResponseEntity.ok().build();
    }
}
